#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <signal.h>
#include <errno.h>

static int g_type = -1;
static int g_length = -1;
static int g_current = -1;
static char* g_data = NULL;
static int g_obj_sig = 0;

static void ipc_data_handler(char* data, int length)
{
    printf("ipc data: %s\n", data);
}

static void signal_handler(int sig, siginfo_t* info, void* ucontext)
{
    if (sig == g_obj_sig) {
        int data = info->si_value.sival_int;

        if (g_current == -1) {
            g_type = data & 0xFFFF;
            g_length = (data >> 16) & 0xFFFF;
            g_current = 0;
            g_data = malloc(g_length);

            if (!g_data) {
                exit(-1);
            }
        } else {
            int i = 0;

            // 1次处理4个字节
            while ((i < 4) && (g_current < g_length)) {
                g_data[g_current] = (data >> (i * 8)) & 0xFF;
                g_current++;
                i++;
            }
        }

        if (g_current == g_length) {
            ipc_data_handler(g_data, g_length);
            g_type = -1;
            g_length = -1;
            g_current = -1;
            free(g_data);
        }
    }
}

int main(int argc, char* argv[])
{
    struct sigaction act = {0};
    sigset_t set = {0};
    int i = 0;
    
    g_obj_sig = atoi(argv[1]);
    printf("current pid(%d) ...\n", getpid());

    act.sa_sigaction = signal_handler;
    act.sa_flags = SA_SIGINFO;
    
    sigaddset(&act.sa_mask, g_obj_sig);
    
    sigaction(g_obj_sig, &act, NULL);

    while (1) {
        sleep(1);
    }

    return 0;
}

